"use client";
import {
  Button,
  Form,
  Input,
  Table,
  Modal,
  DatePicker,
  Select,
  Space,
  Card,
  Row,
  Col,
  Statistic,
  Tag,
} from "antd";
import { Pagination } from "@/utils/db/dbTools";
import React, { useEffect, useState } from "react";
import { system } from "@/forent-api/api";
import { App } from "antd";
import type { ColumnsType } from "antd/es/table";
import {
  DeleteOutlined,
  EyeOutlined,
  FilterOutlined,
  ReloadOutlined,
} from "@ant-design/icons";
import dayjs from "dayjs";
import TextArea from "antd/es/input/TextArea";
import { tableColumns } from "./tools";

const { RangePicker } = DatePicker;
const { Option } = Select;

interface LogItem {
  id: number;
  user_name: string;
  module: string;
  operation_name: string;
  request_method: string;
  operation_ip: string;
  status: number;
  operation_time: string;
  cost_time: number;
  error_msg: string;
}

interface LogStats {
  todayCount: number;
  todayErrorCount: number;
  totalCount: number;
  moduleStats: { module: string; count: number }[];
}

const SystemLogContent: React.FC = () => {
  const [pagination, setPagination] = useState<Pagination>({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const { message, modal } = App.useApp();

  const [searchForm] = Form.useForm();
  const [logTableData, setLogTableData] = useState<LogItem[]>([]);
  const [loading, setLoading] = useState(false);
  const [isDetailModalVisible, setIsDetailModalVisible] = useState(false);
  const [currentLogDetail, setCurrentLogDetail] = useState<LogItem | null>(
    null
  );
  const [logStats, setLogStats] = useState<LogStats>({
    todayCount: 0,
    todayErrorCount: 0,
    totalCount: 0,
    moduleStats: [],
  });

  useEffect(() => {
    getLogListAction();
    getLogStatsAction();
  }, [pagination.current]);

  /**
   * 获取日志列表
   */
  const getLogListAction = () => {
    setLoading(true);
    const searchValues = searchForm.getFieldsValue();
    const params = {
      page: pagination.current,
      pageSize: pagination.pageSize,
      ...searchValues,
      startTime: searchValues.timeRange?.[0]?.format("YYYY-MM-DD HH:mm:ss"),
      endTime: searchValues.timeRange?.[1]?.format("YYYY-MM-DD HH:mm:ss"),
    };

    // 移除 timeRange 字段，因为后端不需要
    delete params.timeRange;

    system.getLogList(params)
      .then((res) => {
        setLogTableData(res.data.data || []);
        setPagination({
          ...pagination,
          current: res.data.page,
          total: res.data.total as number,
        });
      })
      .finally(() => {
        setLoading(false);
      });
  };

  /**
   * 获取日志统计
   */
  const getLogStatsAction = () => {
    system.getLogStats().then((res) => {
      setLogStats(
        res.data || {
          todayCount: 0,
          todayErrorCount: 0,
          totalCount: 0,
          moduleStats: [],
        }
      );
    });
  };

  /**
   * 切换table的页码
   */
  const handleTableChange = (pagination: any) => {
    setPagination((prev: any) => ({ ...prev, current: pagination.current }));
  };

  /**
   * 搜索日志
   */
  const handleSearch = () => {
    setPagination((prev) => ({ ...prev, current: 1 }));
    getLogListAction();
  };

  /**
   * 重置搜索
   */
  const handleReset = () => {
    searchForm.resetFields();
    setPagination((prev) => ({ ...prev, current: 1 }));
    getLogListAction();
  };

  /**
   * 查看日志详情
   */
  const viewLogDetail = (record: LogItem) => {
    setCurrentLogDetail(record);
    setIsDetailModalVisible(true);
  };

  /**
   * 清空日志
   */
  const clearLogs = () => {
    modal.confirm({
      title: "确认清空日志",
      content: "确定要清空所有日志吗？此操作不可恢复！",
      onOk: () => {
        return system.clearLogs({}).then(() => {
          message.success("清空成功");
          getLogListAction();
          getLogStatsAction();
        });
      },
    });
  };

  /**
   * 清空指定天数前的日志
   */
  const clearOldLogs = () => {
    modal.confirm({
      title: "清空历史日志",
      content: (
        <div>
          <p>请选择要保留的天数：</p>
          <Select defaultValue={30} style={{ width: 200 }} id="daysSelect">
            <Option value={7}>保留7天</Option>
            <Option value={30}>保留30天</Option>
            <Option value={90}>保留90天</Option>
            <Option value={180}>保留180天</Option>
          </Select>
        </div>
      ),
      onOk: () => {
        const days =
          (document.getElementById("daysSelect") as any)?.value || 30;
        return system.clearLogs({ days: parseInt(days) }).then(() => {
          message.success("清空成功");
          getLogListAction();
          getLogStatsAction();
        });
      },
    });
  };

  const columns: any = tableColumns(viewLogDetail);

  return (
    <div className="h-full flex flex-col">
      {/* 统计卡片 */}
      <Row gutter={8} className="mb-2">
        <Col span={6}>
          <Card>
            <Statistic title="今日日志" value={logStats.todayCount} />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="今日异常"
              value={logStats.todayErrorCount}
              valueStyle={{ color: "#cf1322" }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic title="总日志数" value={logStats.totalCount} />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="成功率"
              value={
                logStats.todayCount > 0
                  ? (
                      ((logStats.todayCount - logStats.todayErrorCount) /
                        logStats.todayCount) *
                      100
                    ).toFixed(1)
                  : 100
              }
              suffix="%"
            />
          </Card>
        </Col>
      </Row>

      {/* 搜索表单 */}
      <Card>
        <Form form={searchForm} layout="inline">
          <Form.Item name="module" label="操作模块">
            <Input placeholder="请输入操作模块" style={{ width: 140 }} />
          </Form.Item>
          <Form.Item name="operationName" label="操作名称">
            <Input placeholder="请输入操作名称" />
          </Form.Item>
          <Form.Item name="userName" label="用户名">
            <Input placeholder="请输入用户名" />
          </Form.Item>
          <Form.Item name="status" label="状态">
            <Select placeholder="请选择状态" allowClear style={{ width: 120 }}>
              <Option value={0}>成功</Option>
              <Option value={1}>失败</Option>
            </Select>
          </Form.Item>
          <Form.Item name="timeRange" label="时间范围">
            <RangePicker
              showTime
              format="YYYY-MM-DD HH:mm:ss"
              style={{ width: 230 }}
            />
          </Form.Item>
          <Form.Item>
            <Space>
              <Button
                type="primary"
                icon={<FilterOutlined />}
                onClick={handleSearch}
              >
                搜索
              </Button>
              <Button icon={<ReloadOutlined />} onClick={handleReset}>
                重置
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>

      <Card className="mt-2">
        {/* 操作按钮 */}
        <div className="flex gap-2">
          <Button onClick={clearOldLogs}>清空历史日志</Button>
          <Button danger icon={<DeleteOutlined />} onClick={clearLogs}>
            清空所有日志
          </Button>
        </div>
        {/* 日志表格 */}
        <div className="flex-1 system-log-table mt-4">
          <Table
            columns={columns}
            dataSource={logTableData}
            pagination={{ ...pagination, position: ["bottomCenter"] }}
            onChange={handleTableChange}
            loading={loading}
            scroll={{ y: "calc(100vh - 464px)" }}
            rowKey="id"
            size="small"
          />
        </div>
      </Card>

      {/* 日志详情弹窗 */}
      <Modal
        title="日志详情"
        open={isDetailModalVisible}
        onCancel={() => setIsDetailModalVisible(false)}
        footer={[
          <Button key="close" onClick={() => setIsDetailModalVisible(false)}>
            关闭
          </Button>,
        ]}
        width={800}
      >
        {currentLogDetail && (
          <div>
            <Row gutter={16}>
              <Col span={12}>
                <p>
                  <strong>用户名：</strong>
                  {currentLogDetail.user_name}
                </p>
              </Col>
              <Col span={12}>
                <p>
                  <strong>操作模块：</strong>
                  {currentLogDetail.module}
                </p>
              </Col>
            </Row>
            <Row gutter={16}>
              <Col span={24}>
                <p>
                  <strong>操作名称：</strong>
                  {currentLogDetail.operation_name}
                </p>
              </Col>
            </Row>
            <Row gutter={16}>
              <Col span={12}>
                <p>
                  <strong>请求方法：</strong>
                  {currentLogDetail.request_method}
                </p>
              </Col>
              <Col span={12}>
                <p>
                  <strong>IP地址：</strong>
                  {currentLogDetail.operation_ip}
                </p>
              </Col>
            </Row>
            <Row gutter={16}>
              <Col span={12}>
                <p>
                  <strong>状态：</strong>
                  <Tag
                    color={currentLogDetail.status === 0 ? "success" : "error"}
                  >
                    {currentLogDetail.status === 0 ? "成功" : "失败"}
                  </Tag>
                </p>
              </Col>
              <Col span={12}>
                <p>
                  <strong>耗时：</strong>
                  {currentLogDetail.cost_time}ms
                </p>
              </Col>
            </Row>
            <Row gutter={16}>
              <Col span={24}>
                <p>
                  <strong>操作时间：</strong>
                  {dayjs(currentLogDetail.operation_time).format(
                    "YYYY-MM-DD HH:mm:ss"
                  )}
                </p>
              </Col>
            </Row>
            {currentLogDetail.error_msg && (
              <Row gutter={16}>
                <Col span={24}>
                  <p>
                    <strong>错误信息：</strong>
                  </p>
                  <TextArea
                    value={currentLogDetail.error_msg}
                    rows={3}
                    readOnly
                  />
                </Col>
              </Row>
            )}
          </div>
        )}
      </Modal>
    </div>
  );
};

export default function SystemLog() {
  return (
    <div className="h-full px-2 rounded-[10px]">
      <SystemLogContent />
    </div>
  );
}
